package tota.tuples.hop;

/**
 * <p>Title: TOTA</p>
 * <p>Description: TOTA</p>
 * <p>Copyright: Copyright (c) 2002</p>
 * <p>Company: DII - DISMI</p>
 * @author Marco Mamei
 * @version 1.0
 */

import java.util.*;
import tota.tuples.*;
import tuplespace.tuples.Tuple;
import lime.tuples.*;

public class RandomTuple extends HopTuple
{
 public String dest = new String();
 /*****************************************************************************/
 /*     METHODS THAT MUST BE IMPLEMENTED BUT ARE NOT PART OF THE MODEL        */
 /*****************************************************************************/
 protected int[] getTupleColor()
 {
  int val = 10+(hop*255)/10;
  if(val > 255)
   val = 255;
  if(val < 10)
   val = 10;

  int[] color = new int[3];
  color[0] = val;
  color[1] = val;
  color[2] = val;

  return color;
 }

 /*****************************************************************************/
 /*         METHODS THAT MUST BE IMPLEMENTED AND ARE PART OF THE MODEL        */
 /*****************************************************************************/
 public boolean decideEnter()
 {
  boolean cond0 = tota.keyrd(this) == null;
  boolean cond1 = tota.toString().equals(this.getSourceFromId());
  boolean cond2 =  tota.toString().equalsIgnoreCase(dest);
  return cond0 && (cond1 || cond2);
 }

 public boolean decidePropagate()
 {
  Vector a = getPossibleDestinations();

  if(a.size()==0)
   return false;

  int index = (int)(Math.random()*(double)a.size());
  dest = (String)a.get(index);
  return true;
 }

 /*****************************************************************************/
 /*                          TUPLE SPECIFIC METHODS                           */
 /*****************************************************************************/
 private Vector getPossibleDestinations()
 {
	 
  Vector x = tota.read(new Tuple("<content=*>"));
  for(int i=0; i<x.size(); i++)
   System.out.println(((Tuple)x.get(i)).serialize());
	 
  PresenceTuple pres = new PresenceTuple("<peer=*>");
  Vector n = tota.keyrdOneHop(pres);
  Vector neighbors = new Vector();
  for(int i=0;i<n.size();i++)
  {
   String pName = ((PresenceTuple)n.get(i)).peer;
   neighbors.add(pName);
  }

  /* remove from the previous list the peer where the tuple is already stored */
  Vector v = tota.keyrdOneHop(this);
  if(v == null)
   return neighbors;
  for(int i=0; i<v.size(); i++)
  {
   RandomTuple t = (RandomTuple)v.elementAt(i);
   neighbors.remove(t.from);
  }
  return neighbors;
 }
}